package tcp.socket;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLEncoder;



/**
 * @author Han
 */
public class SocketHttpClientGET {
	public static void main(String[] args) throws Exception {
		for(int i = 0;i<1;i++){
			testNet();
		}
	}
	
	static void testNet() throws Exception{
		
		
		Socket socket = new Socket("123.103.86.53",80);
		//拼接http协议的文本
		StringBuffer sb = new StringBuffer("GET / HTTP/1.1\r\n");
		sb.append("Host:www.baidu.com\r\n");
		sb.append("Content-Type: application/x-www-form-urlencoded\r\n");
		sb.append("Accept:*/*\r\n");
		sb.append("Accept-Language:zh-cn\r\n");
		sb.append("Accept-Encoding:gzip,deflate\r\n");
		sb.append("userid:587707\r\n");
		sb.append("User-Agent:Mozzila/4.0(compatible;MSIE 6.0;Windows NT 5.0)\r\n");
		sb.append("Connection:Keep-Alive\r\n");
		//请求头和请求体之间，空行分隔，同响应
		sb.append("\r\n");
		//设置参数
		
		OutputStream socketOut = socket.getOutputStream();
		socketOut.write(sb.toString().getBytes());
		socket.shutdownOutput();
		//这里不加读取的话，类似push，可以节省时间
		InputStream is = socket.getInputStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte [] bt = new byte[1024];
		int len=-1;
		while((len=is.read(bt))!=-1){
			bos.write(bt,0,len);
		}
		System.out.println(new String(bos.toByteArray()));
//		BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//		String line = null;
//		while((line = br.readLine()) != null){
//			System.out.println(line);
//		}
//		br.close();
		is.close();
		socket.close();
		System.out.println("over");
	}
}
